package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmnfeign.DictFeignClient;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.repository.ScheduleRepository;
import com.atguigu.yygh.hosp.service.DepartmentService;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author liking
 * @Description
 * @Date 2025/5/2
 * @Version 1.0
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository repository;

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void saveHospital(Map<String, Object> parameMap) {
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        Map<String, Object> parameMap = HttpRequestHelper.switchMap(parameterMap);
        String jsonString = JSONObject.toJSONString(parameMap);
        Hospital hospital = JSONObject.parseObject(jsonString, Hospital.class);

        Hospital hospitalDb = repository.getHospitalByHoscode(hospital.getHoscode());
        if (hospitalDb != null) {
            hospital.setId(hospitalDb.getId());
            hospital.setCreateTime(hospitalDb.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
//            repository.save(hospital);
        } else {
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
        }
        repository.save(hospital);


    }


    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        Hospital hospital = repository.getHospitalByHoscode(hoscode);
        return hospital;
    }


    @Override
    public void saveDepartment(Map<String, Object> parameMap) {
        String jsonString = JSONObject.toJSONString(parameMap);
        Department department = JSONObject.parseObject(jsonString, Department.class);
        Department departmentDB = departmentService.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (Objects.isNull(departmentDB)) {
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
        } else {
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
        }
        departmentService.save(department);
    }

    @Override
    public void saveSchedule(Map<String, Object> paramMap) {
        String s = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(s, Schedule.class);
        Schedule targetSchedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
        if (null != targetSchedule) {
//值copy不为null的值，该方法为自定义方法
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(targetSchedule);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            scheduleRepository.save(schedule);
        }

    }

    @Override
    public Page<Schedule> findScheduleAll(Integer pageNum, Integer pageSize, ScheduleQueryVo scheduleQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
//0为第一页
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);


        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);

//创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

//创建实例
        Example<Schedule> example = Example.of(schedule, matcher);
        Page<Schedule> pages = scheduleRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void removeScheduleByHoscodeAndHosScheduleId(String hoscode, String hosScheduleId) {
        scheduleRepository.removeScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
    }

    @Override
    public Page<Hospital> getHospitalList(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
//0为第一页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

//创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = repository.findAll(example, pageable);
        pages.getContent().forEach(item -> {
            String hostype = dictFeignClient.getNameByValueAndDictCode(item.getHostype(), "Hostype");

            item.getParam().put("hostypeString", hostype);
            String provinceString = dictFeignClient.getNameByValue(item.getProvinceCode());
            String cityString = dictFeignClient.getNameByValue(item.getCityCode());
            String districtString = dictFeignClient.getNameByValue(item.getDistrictCode());

            item.getParam().put("fullAddress", provinceString + cityString + districtString + item.getAddress());

        });

        return pages;

    }

    @Override
    public void updateStatus(String id, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = repository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            repository.save(hospital);
        }


    }

    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital1 = repository.findById(id).get();
        Hospital hospital = this.packHospital(hospital1);
        result.put("hospital", hospital);

//单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
//不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    private Hospital packHospital(Hospital item) {
        String hostype = dictFeignClient.getNameByValueAndDictCode(item.getHostype(), "Hostype");
        item.getParam().put("hostypeString", hostype);
        String provinceString = dictFeignClient.getNameByValue(item.getProvinceCode());
        String cityString = dictFeignClient.getNameByValue(item.getCityCode());
        String districtString = dictFeignClient.getNameByValue(item.getDistrictCode());

        item.getParam().put("fullAddress", provinceString + cityString + districtString + item.getAddress());
        return item;
    }

    @Override
    public String getHospName(String hoscode) {
        return repository.getHospitalByHoscode(hoscode).getHosname();
    }
}
